#include "TextureDepot.h"
#include "RawTexture.h"
#include "SubTexture.h"
#include "GraphicsInternals.h"
#include "SDL_opengl.h"
#include "SDL_image.h"
#include <iostream>

namespace k2graphics
{

TextureDepot::TextureDepot()
{
	for(int i = 0; i < MAX_TEXTURES; ++i)
	{
		_textures[i] = 0;
	}
}

void TextureDepot::setTexture(AbstractTexture* src, int destSlot)
{
	if(_textures[destSlot] != NULL)
	{
		std::cout << "Tried to set already set texture. Aborting.\n";
		return;
	}

	_textures[destSlot] = src;
}

AbstractTexture* TextureDepot::getTexture(int slot)
{
	return _textures[slot];
}

int TextureDepot::loadRawTextureFromFile(std::string& filename, int textureSlot)
{
	// textureSlot == -1 indicates that we should use any available slot
	if(textureSlot == -1)
	{
		for(int i = 0; i < MAX_TEXTURES; ++i)
		{
			if(_textures[i] == NULL)
			{
				textureSlot = i;
				break;
			}
		}
	}

	// if no slot found at this point, return an error
	if(textureSlot == -1 || _textures[textureSlot] != NULL)
	{
		std::cout << "No free texture slot.\n";
		return -1;
	}

	// load the image
	SDL_Surface *image;
	image=IMG_Load(filename.c_str());
	if(!image) {
		std::cout << "IMG_Load Error: " << IMG_GetError() << std::endl;
		// return fail condition
		return -1;
	}

	// create the raw texture (note that it gets OpenGL handle of its texture slot + 1, since zero
	// is an invalid OpenGL texture handle)
	RawTexture* theNewTexture = new RawTexture(textureSlot + 1);

	// load in the actual texture data from the surface
	theNewTexture->glTextureFromSDLSurface(image);

	_textures[textureSlot] = theNewTexture;

	// release the SDL surface since we don't need it anymore
	SDL_FreeSurface(image);

	return textureSlot;
}

int TextureDepot::createSubTexture(int srcTex, int destTex, float left, float top, float width, float height)
{
	// destTex == -1 indicates that we should use any available slot
	if(destTex == -1)
	{
		for(int i = 0; i < MAX_TEXTURES; ++i)
		{
			if(_textures[i] == NULL)
			{
				destTex = i;
				break;
			}
		}
	}

	// if no slot found at this point, return an error
	if(destTex == -1 || _textures[destTex] != NULL)
	{
		std::cout << "No free texture slot.\n";
		return -1;
	}

	if(_textures[srcTex] == NULL)
	{
		std::cout << "No source texture.\n";
		return -1;
	}

	SubTexture* newTex = new SubTexture(_textures[srcTex]);
	newTex->setSubRect(left, top, width, height);
	_textures[destTex] = newTex;

	return destTex;
}

}
